package ch.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

/** Classe per la gestione della singola richiesta SSL
 * 
 * @author Giovanni Franza - GPLv3 - 8/6/2011
 *
 */

public class SSLWorker extends SSL {

	private Socket socket;
	private SSL ssl;

	/** Construttore .
	 *
	 * @param socket - socket su cui opera
	 * @param pop - riferimenti al gestore di protocollo
	 * 
	 */

	public SSLWorker( Socket socket, SSL ssl ) {
		this.socket = socket;
		this.ssl = ssl;
	}
	
	/** Il run fa tutto il lavoro.
	 *
	 */
	
	public void run() {
		try {
		    // Create streams to securely send and receive data to the client
			BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );				
			OutputStream out = socket.getOutputStream();	
		    // Read from in and write to out...
		    String page="";
		    int length = 0;
		    String headers = new String();
		    for(int j=0;;j++) {
		    	// reading the headers
		    	String request = in.readLine();
		    	if( request.startsWith( "Content-Length:") ) {
		    		length = Integer.parseInt( request.substring( 15 ).trim() );
		    	}
		    	headers = headers.concat( request+"<BR>\n" );
		    	if( request == null || request.equals("") ){
		    		break;
		    	}
		    	// getting  name from GET (only header managed)
		    	if( request.startsWith("GET") || request.startsWith("POST")) {
		    		page=request.substring(4).trim();
		    		for( int k=0; k<page.length(); k++ ){
		    			if( page.charAt(k)==' ' || page.charAt(k)=='?' ) {
		    				page=page.substring(0, k);
		    				break;
		    			}
		    		}
		    	}
		    }
		    if( length > 0 ) {
			    char a[] = new char[length];
			    in.read(a, 0, length );
			    headers = headers.concat( String.valueOf(a, 0, length ) );
		    }
		    
			String content = "text/html; charset=iso-8859-1";
			// qui chiama l'applicazione
			ServerHandler serverhandler = ssl.getHandler( page );
			if( serverhandler != null ) {
				String response = ssl.getHandler( page ).run( page + "\r\n" + headers );
				int len = (int)response.length();
			    out.write(("HTTP/1.1 200 OK\nContent-length: "+len+"\nContent-Type: "+content +"\n\n").getBytes() );
			    out.write( response.getBytes());
		    } else {
				    out.write(("HTTP/1.1 404 Not found\n\n").getBytes() );
			}

			// close files
		    out.close();
		    in.close();
		} catch(IOException e) {
			System.out.println(e);
		}
	}
}
